<?php


namespace app\self\controller;


use think\Build;
use think\cache\driver\Redis;
use think\Controller;
use think\Exception;
use think\Request;
use think\Db;

class Init extends Controller
{
    protected $database = '';

    protected $type = '';

    protected $fields = [];

    protected $token = '';


    public function _initialize(Request $request = null)
    {

        $redis = new Redis();
        $token = $redis->get(get_user_id());
        $this->token = $token;
        try {
            if(empty($this->database))
            {
                $this->database = $this->database();
            }
            if(empty($this->type))
            {
                $this->type = $this->databaseField()['remark'];
            }
        }catch(Exception $e)
        {

        }

    }

    public function databaseField()
    {
        return [];
    }

    /**
     * use   表名
     * user  Hugh
     * date  2021/7/13 9:47
     */
    public function database()
    {

        $module = Request::instance()->module();
        $controller = Request::instance()->controller();

        $database = $module.'_'.strtolower($controller);
        return $database;
    }



    /**
     * use   初始化
     * user  Hugh
     * date  2021/7/13 9:56
     */
    public function init()
    {
        $module = Request::instance()->module();
        $controller = Request::instance()->controller();

        //新建菜单
        if(true)
        {
            $menu = $this->menu();
            $menu['url'] = '/'.$module.'/'.$controller.'/index';
            $menu['status'] = '正常';
            $hasMenu = Db::name('s_menu')
                ->where($menu)
                ->find();
            if(empty($hasMenu)){
                DB::name('s_menu')->insert($menu);
            }
            var_dump('菜单已生成!');
        }

        //建表
        if(true)
        {
            $databaseField = $this->databaseField(); // 表字段
            $database = $this->database(); // 表名
            $prefix = config("database.prefix");
            $database = $prefix.$database;
            $dropSql = 'DROP TABLE IF EXISTS '.$database;;

            $sql = "CREATE TABLE ".$database." (
            id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,";
            foreach($databaseField['database'] as $k =>$v)
            {
                if($v['type'] == 'date')
                {
                    $sql .= "`".$v['field']."` ".$v['type']." NULL COMMENT '".$v['title']."',";
                }
                else{
                    if(isset($v['default']))
                    {
                        $sql .= "`".$v['field']."` ".$v['type']."(".$v['length'].")  NULL DEFAULT '".$v['default']."' COMMENT '".$v['title']."',";

                    }
                    else{
                        $sql .= "`".$v['field']."` ".$v['type']."(".$v['length'].")  NULL COMMENT '".$v['title']."',";

                    }
                }
            }
            $sql = substr($sql,0,strlen($sql)-1);
            $sql .=" ) ENGINE = InnoDB AUTO_INCREMENT = 224 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '".$databaseField['remark']."' ROW_FORMAT = Dynamic;";
            DB::startTrans();
            try {
                DB::query($dropSql);
                DB::query($sql);
                DB::commit();
                echo "<br>";
                var_dump('数据表创建成功!');
            }catch(Exception $e)
            {
                DB::rollback();
                var_dump('数据表创建失败');
            }
        }

        //创建文件
        if(true)
        {
            //todo 自动生成文件
            //创建view层文件夹
            $build = [
                $module=>[
                    '__dir__'=>['view'],

                    'view'=>[
                        strtolower($controller).'/index',
                        strtolower($controller).'/edit'
                    ],
                ]
            ];
            //创建文件
            Build::run($build);
            echo "<br>";
            var_dump('文件创建成功');
        }

        //写入代码
        if(true)
        {
            //文件写入内容
            $field = $this->databaseField();
            $columns = [];
            $columns[] = ['field'=>'','checkbox'=>true];
            foreach($field['database'] as $k =>$v)
            {
                if(in_array('show',$v))
                {
                    $attr = [
                        'field'=>$v['field'],
                        'title'=>$v['title'],
                    ];
                    if (isset($v['add']) && $v['add'] == 'img')
                    {
                        $attr['formatter'] = 'bannerImg';
                    }
                    $columns[] = $attr;
                }
            }
            $getData = '/'.$module.'/'.$controller;
            $path =APP_PATH.$module."/view/".strtolower($controller)."/index.html";
            $content = "{extend name='self@public/index'}
{block name=\"main\"}
<style>
    img{
        width:50px;height:50px;
    }
</style>
<!--表格-->
<script>
    //获取数据接口
    let getData = '".$getData."';
    //表格列
    let columns = ".json_encode($columns).";

    let area = ['20%', '30%'];
</script>
{/block}
            ";
            file_put_contents($path,$content);
            $path =APP_PATH.$module."/view/".strtolower($controller)."/edit.html";
            $content = "{extend name='self@public/detail'}";
            file_put_contents($path,$content);
            echo "<br>";
            var_dump('前台页面代码写入成功');
        }
    }


    /**
     * use  搜索条件字段
     * by   hugh
     * time 2020/12/28 14:33
     */
    public function searchWhere()
    {
        $field = $this->databaseField()['database'];
        $fields = [];
        foreach($field as $k => $v)
        {
            $fields[] = $v['field'];
            if(!isset($v['search']) && !in_array('search',$v))
            {
                unset($field[$k]);
            }
        }
        $this->fields = $fields;

        $field = array_values($field);
        $search = [];
        $data = [];
        $selected = $this->selectOption();
        foreach($field as $k =>$v)
        {
            if(!isset($v['search']))
            {
                $search[] = ['field'=>$v['field'],'name'=>$v['title']];
            }
            else{
                $search[] = ['field'=>$v['field'],'name'=>$v['title'],'type'=>$v['search']];
                foreach($selected[$v['field']] as $k1 =>$v1)
                {
                    $data[$v['field']][] = ['value'=>$v1,'key'=>$v1];
                }
            }
        }
        $this->assign('search',$search);
        $this->assign('searchJs',json_encode($search));
        $this->selectData($data);
    }

    public function selectData($data)
    {
        $this->assign('selectData',$data);
    }

    public function mapSelf()
    {
        if(in_array('is_delete',$this->fields))
        {
            return ['is_delete'=>0];
        }
        else{
            return [];
        }
    }

    public function getField()
    {
        $id = input('id/d',0);
        $result = DB::name($this->database)
            ->where(['id'=>$id])
            ->find();
        $field = $this->databaseField()['database'];
        $selectOption = $this->selectOption();
        $edit = [];
        foreach($field as $k =>$v)
        {
            $attr = [];

            if(isset($v['add']) || in_array('add',$v))
            {
                if(in_array('notNull',$v))
                {
                    $attr['notNull'] = true;
                }
                if(isset($v['search']) && $v['search'] == 'select')
                {
                    $attr['type'] = 'select';
                    $attr['option'] = $selectOption[$v['field']];
                }
                if(isset($v['add']) && $v['add'] == 'img')
                {
                    $attr['img'] = true;
                }
                $attr['field'] = $v['field'];
                $attr['name'] = $v['title'];
                $attr['value'] = $result[$v['field']];
                $edit[] = $attr;
            }
        }
        return $edit;
    }

    /**
     * use   数据验证
     * user  Hugh
     * date  2021/3/30 13:55
     * @param $data
     * @param $id
     */
    public function postVerification($data,$id)
    {
        $field = $this->databaseField();
        foreach($field as $k =>$v)
        {
            if(in_array('notNull',$v))
            {
                if(empty($data[$v['field']])) return fieldEmpty($v['title']); //字段不能为空
            }
        }

    }





}